package com.itcodai.controller.course12;

import com.itcodai.entity.User;
import com.itcodai.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;

import javax.servlet.ServletContext;

/**
 * @author c-fanqj
 * @date 2023/4/5
 * @apiNote 使用ApplicationListener来初始化一些数据到application域中的监听器
 * 1、监听Servlet上下文对象：初始化数据，用于缓存
 */
//@Component
public class MyServletContextListener
        implements ApplicationListener<ContextRefreshedEvent> {

    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        // 先获取到application上下文
        ApplicationContext applicationContext = contextRefreshedEvent.getApplicationContext();
        // 获取对应的service
        UserService userService;
        userService = applicationContext.getBean(UserService.class);
        //userService = applicationContext.getBean(UserServiceImpl.class);
        User user;
        //user = userService.getUser(2L);
        user = userService.getUser();
        // 获取application域对象，将查到的信息放到application域中
        ServletContext application = applicationContext.getBean(ServletContext.class);
        application.setAttribute("user", user);
    }




}
